package com.dlkw.easyroom.compiler.classkeeper;

import com.dlkw.easyroom.compiler.Tools;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.WildcardTypeName;

import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class DaoClass extends BaseClass {
    private final String entityClass;
    private String daoGetterName;

    public DaoClass(TypeElement element) {
        super(element);
        TypeMirror entityType = Tools.resolveEntityType(element, "com.dlkw.easyroom.BaseDao");
        if (null == entityType) {
            throw new RuntimeException("DaoClass must implement BaseDao");
        }
        this.entityClass = entityType.toString();
    }

    @Override
    protected void fillTypeBuilder(TypeSpec.Builder builder) {
        ClassName roomDatabaseClassName = ClassName.bestGuess(entityClass);
        WildcardTypeName roomDbSubtype = WildcardTypeName.subtypeOf(roomDatabaseClassName);
        TypeName classOfRoomDb = ParameterizedTypeName.get(
                ClassName.get(Class.class),
                roomDbSubtype
        );
        builder.addField(FieldSpec.builder(classOfRoomDb, "ENTITY_CLASS", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                .initializer("$T.class", ClassName.bestGuess(entityClass)).build());
    }
}
